<template>
  <div class="page-account">
    <div class="page-logo">
      <div class="page-logo-wp">
        <img src="../../assets/imgs/logo.png" alt="" />
      </div>
    </div>
    <div class="container">
      <template v-if="fullWidth > 768">
        <div class="swiper-wp">
          <swiper :options="swiperOption" class="swiperPross">
            <swiper-slide v-for="(item, index) in sliderList" :key="index" class="swiperPic">
              <img :src="item.img" @click="jump(item.url)">
            </swiper-slide>
            <div slot="pagination" class="swiper-pagination" />
          </swiper>
        </div>
      </template>
      <div class="index_from page-account-container">
        <div class="page-account-top ">
          欢迎来到桦叶物流运营端
        </div>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on"
          label-position="left" @keyup.enter="handleLogin">
          <el-form-item prop="account" class="form-item">
            <el-input ref="account" v-model="loginForm.account" placeholder="用户名" name="username" type="text"
              tabindex="1" autocomplete="on">
              <i class="el-icon-user-solid" slot="prefix"></i>
            </el-input>
          </el-form-item>

          <el-form-item prop="pwd" class="form-item">
            <el-input :key="passwordType" ref="pwd" v-model="loginForm.pwd" :type="passwordType" placeholder="密码"
              :show-password="false" name="pwd" tabindex="2" auto-complete="on">
              <span class="pwd-img" slot="prefix">
                <img src="@/assets/imgs/suo.png" alt="">
              </span>
            </el-input>
            <span class="show-pwd" @click="showPwd">
              <!-- <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" /> -->
              <img :src="passwordType === 'password' ? pwdBolckImg : pwdHiddenImg" alt="">
            </span>
          </el-form-item>

          <el-form-item prop="code" class="captcha-wp form-item">
            <div class="captcha">
              <el-input ref="username" v-model="loginForm.code" placeholder="验证码" name="username" type="text"
                tabindex="3" autocomplete="on" />
              <div class="imgs" @click="getCaptcha()"><img :src="captchatImg"></div>
            </div>
          </el-form-item>

          <div class="acea-row">
            <el-button :loading="loading" type="primary" @click.native.prevent="handleLogin">登录
            </el-button>
            <!--<div class="acea-row footer" @click="onWechat">-->
            <!--<div class="wechat mr10"><img src="../../assets/imgs/weixin.png"></div>-->
            <!--<span>微信</span>-->
            <!--</div>-->
            <div class="forget-pwd">
              <a>忘记密码?</a>
              <a>找回密码</a>
            </div>
          </div>
        </el-form>
      </div>

    </div>
    <div class="footers">
      <ul class="footer-nav footer-nav-top">
        <li v-for="(nav, i) in footerNav" :key="i"><a :href="nav.url" target="_blank">{{ nav.text }}</a></li>
      </ul>
      <ul class="footer-nav footer-nav-bottom">
        <li v-for="item in links" :key="item.title"><a :href="item.url" target="_blank">{{ item.title }}</a></li>
      </ul>
    </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import "@/assets/js/canvas-nest.min.js";
import { captchaApi } from '@/api/user'
import { getWXCodeByUrl, loginByWxCode } from "@/libs/wechat";
import { getWechatConfig } from "@/api/wxApi";
import { getToken, removeToken, setToken } from '@/utils/auth'

import pwdBolckImg from '@/assets/imgs/psd_block.png';
import pwdHiddenImg from '@/assets/imgs/pad_hiddle.png';
import slideOne from '@/assets/imgs/rz.png';
import slideTwo from '@/assets/imgs/rz2.png';
import slideThree from '@/assets/imgs/rz3.png';
import { log } from 'console';

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length > 12) {
        callback(new Error('密码位数为6-12位'))
      } else {
        callback()
      }
    }
    return {
      pwdBolckImg,
      pwdHiddenImg,
      sliderList: [
        {
          img: slideOne,
          url: 'https://pcsclient.huayestore.cn/',
        },
        {
          img: slideTwo,
          url: 'https://pcsclient.huayestore.cn/',
        },
        {
          img: slideThree,
          url: 'https://pcsclient.huayestore.cn/',
        },
      ],
      footerNav: [
        {
          text: '关于我们',
          url: 'https://pcsclient.huayestore.cn/helps/course',
        },
        {
          text: '联系我们',
          url: 'https://pcsclient.huayestore.cn/',
        },
        {
          text: '联系客服',
          url: 'https://pcsclient.huayestore.cn/helps/service',
        },
        {
          text: '商家入驻',
          url: 'https://pcsclient.huayestore.cn/courtship',
        },
        {
          text: '手机商城',
          url: 'https://sclient.huayestore.cn/',
        },
        {
          text: '企业文化',
          url: 'https://pcsclient.huayestore.cn/helps/culture',
        },
        {
          text: '商务合作',
          url: 'https://pcsclient.huayestore.cn/courtship/contact',
        },
        {
          text: '友情链接',
          url: 'https://pcsclient.huayestore.cn/',
        },
      ],
      links: [
        {
          title: '©2022 桦叶 粤ICP备19099677号',
          href: 'https://beian.miit.gov.cn',
        },
        {
          title: '联系电话：4008919131',
        },
        {
          title: '地址：广东省东莞市东城街道莞樟路东城段234号2栋704室',
        }
      ],
      copyright: '',
      captchatImg: '',
      //swiperList: [],
      //loginLogo: '',
      //backgroundImages: '',
      backgroundImageMo: require("@/assets/imgs/bg.jpg"),
      fullWidth: document.body.clientWidth,
      swiperOption: {
        loop: true,
        // pagination: {
        //   el: '.pagination'
        // },
        autoplay: {
          enabled: true,
          disableOnInteraction: false,
          delay: 3000
        }
      },
      loginForm: {
        account: '', // admin
        pwd: '',
        key: '',
        code: '',
        wxCode: ''
      },
      loginRules: {
        account: [{ required: true, trigger: 'blur', message: '请输入用户名' }], // validator: validateUsername
        pwd: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        code: [{ required: true, message: '请输入正确的验证码', trigger: 'blur' }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    fullWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function () {
          // 打印screenWidth变化的值
          that.timer = false
        }, 400)
      }
    },
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    const _this = this
    document.onkeydown = function (e) {
      if (_this.$route.path.indexOf('login') !== -1) {
        const key = window.event.keyCode
        if (key === 13) {
          _this.handleLogin()
        }
      }
    }
    window.addEventListener('resize', this.handleResize)
  },
  mounted() {
    this.$nextTick(() => {
      if (this.screenWidth < 768) {
        document
          .getElementsByTagName("canvas")[0]
          .removeAttribute("class", "index_bg");
      } else {
        document.getElementsByTagName("canvas")[0].className = "index_bg";
      }
    });
    if (this.loginForm.account === '') {
      this.$refs.account.focus()
    } else if (this.loginForm.pwd === '') {
      this.$refs.pwd.focus()
    }
    this.getCaptcha()
    this.agentWeiXinLogin()
  },
  beforeCreate() {
    if (this.fullWidth < 768) {
      document
        .getElementsByTagName("canvas")[0]
        .removeAttribute("class", "index_bg");
    } else {
      document.getElementsByTagName("canvas")[0].className = "index_bg";
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.handleResize)
    document
      .getElementsByTagName("canvas")[0]
      .removeAttribute("class", "index_bg");
  },
  methods: {
    jump(url) {
      window.open(url, '_blank');
    },
    agentWeiXinLogin() { // 判断是否需要微信公众号登陆
      const _isWechat = this.$wechat.isWeixin();
      if (_isWechat) {
        let code = this.$route.query.code
        let state = this.$route.query.state
        let wxAuthPath = location.origin + '/login';
        //  如果没有code 去获取
        if (null == code) {
          getWXCodeByUrl(wxAuthPath, 'step1');
        }
        // 如果有state=step1 根据code去登陆
        if (state === 'step1') {
          loginByWxCode(code).then(res => {
            sessionStorage.setItem('token', res.token)
            this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
          }).catch(err => {
            // 如果登陆失败，那么输入账号登陆，重新获取code传递给后端做绑定
            getWXCodeByUrl(wxAuthPath, 'step2');
          })
        } else if (state === 'step2') {
          this.loginForm.wxCode = code
        }

      }
    },
    onWechat() {
      let url = this.$route.query.redirect ? this.$route.query.redirect : '/dashboard'
      this.$wechat.oAuth(url, 'login')
    },
    handleResize(event) {
      this.fullWidth = document.body.clientWidth
      if (this.fullWidth < 768) {
        document
          .getElementsByTagName("canvas")[0]
          .removeAttribute("class", "index_bg");
      } else {
        document.getElementsByTagName("canvas")[0].className = "index_bg";
      }
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.pwd.focus()
      })
    },
    handleLogin() {
      const code = this.$route.query.code;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.$wechat.isWeixin()) {
            this.loginForm.wxCode = code
          }
          //登入
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            }).catch((err) => {
              this.loading = false
              //console.log('失败登录',err)
              this.$message.error(err.msg)
              if (this.$wechat.isPhone()) this.$dialog.error(err.msg);
              this.getCaptcha()
            })

        } else {
          return false
        }
      })
    },
    //获取验证码
    getCaptcha() {
      captchaApi().then((res) => {
        this.captchatImg = res.data.code
        this.loginForm.key = res.data.key
        console.log(res.data,res.data.code)
        //console.log('captchatImg', this.loginForm.key)
      }).catch((err) => {
        //console.log(res)
        this.$message.error(err.msg)
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item>>>.el-input--medium .el-input__inner {
  border-radius: 0px;
  border: 1px solid #F1C69A;
  padding-left: 48px;
}

.form-item .captcha>>>.el-input--medium .el-input__inner {
  padding-left: 12px;
}

.form-item>>>.el-input__inner:focus {
  border: 1px solid #F1C69A;
}

.form-item>>>.el-input__prefix {
  left: 0;
  width: 36px;
  background: #F8E3C8;
  border: 1px solid #F1C69A;
  border-right: none;

  i {
    color: #fff;
  }
}

.acea-row>>>.el-button {
  width: 300px;
  height: 40px;
  line-height: 40px;
  background: #FFAE00;
  border: none;
  border-radius: 0px;
  padding: 0;
  margin-top: 20px;

  span {
    font-size: 20px;
    font-weight: 400;
    color: #FFFFFF;
  }
}

.acea-row .forget-pwd {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin-top: 8px;

  a {
    &:first-child {
      font-size: 12px;
      font-weight: 400;
      color: #D2D1CE;
    }

    &:last-child {
      font-size: 12px;
      font-weight: 400;
      color: #26A9DF;
    }
  }

}

.el-icon-user-solid {
  font-size: 20px;
}

.pwd-img {
  width: 100%;
  height: 100%;
  display: inline-block;
  padding-top: 4px;

  img {
    width: 16px;
    height: 20px;
  }
}


$screen-md: 768px;
$font-size-base: 14px;
$animation-time : .3s;
$animation-time-quick : .15s;
$transition-time : .2s;
$ease-in-out : ease-in-out;
$subsidiary-color : #808695;

.footer {
  align-items: center;
  justify-content: center;
  width: 50%;
  height: 36px;
  cursor: pointer;
}

.wechat {
  width: 26px;
  height: 26px;

  img {
    width: 100%;
    height: 100%;
  }
}

.page-logo {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100px;
  background-color: #fff;

  .page-logo-wp {
    width: 1200px;
    margin: 0 auto;
    height: 100%;
    padding-top: 15px;
  }

  img {
    width: 216px;
    height: 66px;
  }
}

.page-account {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  overflow: auto;
  background-color: #FFD4A7;

  &-container {
    flex: 1;
    padding: 32px 0;
    text-align: center;
    width: 384px;
    margin: 0 auto;

    &-result {
      width: 100%;
    }
  }

  &-tabs {
    .ivu-tabs-bar {
      border-bottom: none;
    }

    .ivu-tabs-nav-scroll {
      text-align: center;
    }

    .ivu-tabs-nav {
      display: inline-block;
      float: none;
    }
  }

  &-top {
    padding: 32px 0;

    &-logo {
      img {
        max-height: 75px;
      }
    }

    &-desc {
      font-size: $font-size-base;
      color: $subsidiary-color;
    }
  }

  &-auto-login {
    margin-bottom: 24px;
    text-align: left;

    a {
      float: right;
    }
  }

  &-other {
    margin: 24px 0;
    text-align: left;

    span {
      font-size: $font-size-base;
    }

    img {
      width: 24px;
      margin-left: 16px;
      cursor: pointer;
      vertical-align: middle;
      opacity: 0.7;
      transition: all $transition-time $ease-in-out;

      &:hover {
        opacity: 1;
      }
    }
  }

  .ivu-poptip,
  .ivu-poptip-rel {
    display: block;
  }

  &-register {
    float: right;

    &-tip {
      text-align: left;

      &-title {
        font-size: $font-size-base;
      }

      &-desc {
        white-space: initial;
        font-size: $font-size-base;
        margin-top: 6px;
      }
    }
  }

  &-to-login {
    text-align: center;
    margin-top: 16px;
  }

  &-header {
    text-align: right;
    position: fixed;
    top: 16px;
    right: 24px;
  }
}

.labelPic {
  position: absolute;
  right: 0;
}

@media(max-width: 1200px) {
  .page-logo-wp {
    width: 100%;
    padding-left: 50px;
  }
}

@media (min-width: $screen-md) {
  .page-account {
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
  }

  .page-account-container {
    padding: 32px 0 24px 0;
    position: relative;
  }
}

.page-account {
  display: flex;
}

.page-account .code {
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-account .code .pictrue {
  height: 40px;
}

.swiperPross {
  border-radius: 6px;
  overflow: hidden;
}

.swiper-wp {
  width: 740px;
  height: 420px;
  margin-right: 30px;
}


.swiperPross,
.swiperPic,
.swiperPic img {
  width: 100%;
  height: 100%;
}

.swiperPic img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

.container {
  // height: 400px !important;
  padding: 0 !important;
  /*overflow: hidden;*/
  // border-radius: 6px;
  z-index: 1;
  display: flex;
}

.containerSamll {
  /*width: 56% !important;*/
  width: 670px;
  background: #fff !important;
}

.containerBig {
  width: auto !important;
  background: #f7f7f7 !important;
}

.index_from {
  width: 390px;
  height: 420px;
  background: #FFFFFF;
  opacity: 0.93;
  border-radius: 4px;
  padding: 40px 45px 0;

  .page-account-top {
    font-size: 20px;
    font-weight: 400;
    color: #111111;
    padding: 0;
    text-align: left;
    margin-bottom: 45px;

    .login-form>>>.el-input__inner {

      border-radius: 0px;
    }
  }
}

.btn {
  background: linear-gradient(90deg, rgba(25, 180, 241, 1) 0%, rgba(14, 115, 232, 1) 100%) !important;
}

.el-link.el-link--default {
  color: #808695
}

.footers {
  height: 130px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding-top: 32px;

  .footer-nav {
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;

    li {
      a {
        font-size: 12px;
        font-weight: 400;
        color: #333333;
      }
    }
  }

  .footer-nav-top {
    margin-bottom: 25px;

    li {
      position: relative;
      padding: 0 38px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 1px;
        height: 12px;
        background: #666666;
      }

      &:first-child {
        &::before {
          width: 0;
        }
      }
    }
  }
}

.captcha {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .imgs {
    margin-left: 6px;
    line-height: 0px;

    img {
      cursor: pointer;
      border: 1px solid #F1C69A;
    }
  }
}

$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.imgs {
  img {
    height: 36px;
  }
}

.login-form {
  position: relative;
  max-width: 100%;
  margin: 0 auto;
  overflow: hidden;
}

.tips {
  font-size: 14px;
  color: #fff;
  margin-bottom: 10px;

  span {
    &:first-of-type {
      margin-right: 16px;
    }
  }
}

.svg-container {
  padding: 6px 5px 6px 15px;
  color: $dark_gray;
  vertical-align: middle;
  width: 30px;
  display: inline-block;
}

.show-pwd {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: $dark_gray;
  cursor: pointer;
  user-select: none;

  img {
    width: 18px;
    height: 12px;
    object-fit: cover;
  }

  /deep/.svg-icon {
    vertical-align: 0.3em;
  }
}

.thirdparty-button {
  position: absolute;
  right: 0;
  bottom: 6px;
}

:deep(.el-input__icon .el-icon-user) {
  width: 38px !important;
  height: 38px !important;
  display: inline-block;
  background-color: #F8E3C8 !important;

}
</style>
